import { createSignAuditLog, batchCreateSignAuditLog } from '@/api/campus/trainSignAuditLog'
import store from '@/store'

/**
 * 签到审计日志工具类
 */
class AuditLogger {
  constructor() {
    this.batchLogs = []
    this.batchTimer = null
    this.batchDelay = 2000 // 2秒批量提交
  }

  /**
   * 记录单个签到操作日志
   * @param {Object} logData 日志数据
   * @param {string} logData.operation 操作类型 (MANUAL_SIGN, BATCH_SIGN, MAKEUP_SIGN)
   * @param {string} logData.targetType 目标类型 (TEACHER, BATCH)
   * @param {string} logData.targetId 目标ID
   * @param {string} logData.targetName 目标名称
   * @param {Object} logData.beforeData 操作前数据
   * @param {Object} logData.afterData 操作后数据
   * @param {string} logData.reason 操作原因
   * @param {string} logData.ipAddress IP地址
   * @param {boolean} immediate 是否立即提交
   */
  async logOperation(logData, immediate = false) {
    try {
      const userInfo = store.getters.userInfo || {}
      const auditLog = {
        operation: logData.operation,
        operatorId: userInfo.userId,
        operatorName: userInfo.userName,
        targetType: logData.targetType,
        targetId: logData.targetId,
        targetName: logData.targetName,
        beforeData: JSON.stringify(logData.beforeData || {}),
        afterData: JSON.stringify(logData.afterData || {}),
        reason: logData.reason || '',
        ipAddress: logData.ipAddress || this.getClientIP(),
        operationTime: new Date().toISOString(),
        success: true
      }

      if (immediate) {
        await createSignAuditLog(auditLog)
      } else {
        this.addToBatch(auditLog)
      }
    } catch (error) {
      console.error('记录审计日志失败:', error)
    }
  }

  /**
   * 批量记录签到操作日志
   * @param {Array} logDataList 日志数据列表
   */
  async logBatchOperations(logDataList) {
    try {
      const userInfo = store.getters.userInfo || {}
      const auditLogs = logDataList.map(logData => ({
        operation: logData.operation,
        operatorId: userInfo.userId,
        operatorName: userInfo.userName,
        targetType: logData.targetType,
        targetId: logData.targetId,
        targetName: logData.targetName,
        beforeData: JSON.stringify(logData.beforeData || {}),
        afterData: JSON.stringify(logData.afterData || {}),
        reason: logData.reason || '',
        ipAddress: logData.ipAddress || this.getClientIP(),
        operationTime: new Date().toISOString(),
        success: true
      }))

      await batchCreateSignAuditLog({ logs: auditLogs })
    } catch (error) {
      console.error('批量记录审计日志失败:', error)
    }
  }

  /**
   * 记录操作失败日志
   * @param {Object} logData 日志数据
   * @param {Error} error 错误信息
   */
  async logFailure(logData, error) {
    try {
      const userInfo = store.getters.userInfo || {}
      const auditLog = {
        operation: logData.operation,
        operatorId: userInfo.userId,
        operatorName: userInfo.userName,
        targetType: logData.targetType,
        targetId: logData.targetId,
        targetName: logData.targetName,
        beforeData: JSON.stringify(logData.beforeData || {}),
        afterData: JSON.stringify({ error: error.message }),
        reason: logData.reason || '',
        ipAddress: logData.ipAddress || this.getClientIP(),
        operationTime: new Date().toISOString(),
        success: false,
        errorMessage: error.message
      }

      await createSignAuditLog(auditLog)
    } catch (logError) {
      console.error('记录失败日志失败:', logError)
    }
  }

  /**
   * 添加到批量提交队列
   * @param {Object} auditLog 审计日志
   */
  addToBatch(auditLog) {
    this.batchLogs.push(auditLog)
    
    // 清除之前的定时器
    if (this.batchTimer) {
      clearTimeout(this.batchTimer)
    }
    
    // 设置新的定时器
    this.batchTimer = setTimeout(() => {
      this.flushBatch()
    }, this.batchDelay)
  }

  /**
   * 立即提交批量日志
   */
  async flushBatch() {
    if (this.batchLogs.length === 0) return
    
    try {
      await batchCreateSignAuditLog({ logs: [...this.batchLogs] })
      this.batchLogs = []
    } catch (error) {
      console.error('批量提交审计日志失败:', error)
    }
    
    if (this.batchTimer) {
      clearTimeout(this.batchTimer)
      this.batchTimer = null
    }
  }

  /**
   * 获取客户端IP地址（简单实现）
   */
  getClientIP() {
    // 在实际应用中，可能需要通过API获取真实IP
    return 'Unknown'
  }

  /**
   * 创建手动签到日志数据
   * @param {Object} teacher 老师信息
   * @param {Object} signData 签到数据
   * @param {string} reason 操作原因
   */
  createManualSignLogData(teacher, signData, reason = '') {
    return {
      operation: 'MANUAL_SIGN',
      targetType: 'TEACHER',
      targetId: teacher.id,
      targetName: teacher.name,
      beforeData: {
        status: teacher.originalStatus || 'Absent',
        signTime: teacher.originalSignTime || null
      },
      afterData: {
        status: signData.status,
        signTime: signData.signTime,
        period: signData.period,
        signDate: signData.signDate
      },
      reason
    }
  }

  /**
   * 创建批量签到日志数据
   * @param {Array} teachers 老师列表
   * @param {Object} signData 签到数据
   * @param {string} reason 操作原因
   */
  createBatchSignLogData(teachers, signData, reason = '') {
    return teachers.map(teacher => ({
      operation: 'BATCH_SIGN',
      targetType: 'TEACHER',
      targetId: teacher.id,
      targetName: teacher.name,
      beforeData: {
        status: teacher.originalStatus || 'Absent',
        signTime: teacher.originalSignTime || null
      },
      afterData: {
        status: signData.status,
        signTime: signData.signTime,
        period: signData.period,
        signDate: signData.signDate
      },
      reason
    }))
  }


}

// 创建单例实例
const auditLogger = new AuditLogger()

// 页面卸载时确保批量日志提交
window.addEventListener('beforeunload', () => {
  auditLogger.flushBatch()
})

export default auditLogger

// 导出常用方法
export const {
  logOperation,
  logBatchOperations,
  logFailure,
  createManualSignLogData,
  createBatchSignLogData
} = auditLogger